# GNAFU - "Ground, Navy and Air Fuck-Up" real-time strategy game
# Copyright (C) 2008-2009 k0wax <k0waxk0wax@gmail.com>
#
# This file is part of GNAFU.
#
# GNAFU is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GNAFU is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNAFU.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import division, absolute_import

def get_capacity(obj, cargo_t):
    # FIXME store cargo_max_... somewhere else
    attr = 'cargo_cap_%s' % cargo_t
    return getattr(obj, attr) if hasattr(obj, attr) else None

def get_max_transfer_amg(src, dst, cargo_t):
    '''return max posible transfer_amoung of `cargo_t` from `src` to `dst` (per transaction)'''
    src_transfer_rate = 1500 # FIXME hardcoded
    dst_transfer_rate = 1500 # transfer rate per transaction (say t=10 secs)
    max_amg = min(src_transfer_rate, dst_transfer_rate)
    dst_cap = get_capacity(dst, cargo_t)
    # check dst
    trans_amg = max_amg if (dst.cargo[cargo_t] + max_amg) <= dst_cap \
                        else dst_cap - dst.cargo[cargo_t]
    # check src
    trans_amg = trans_amg if (src.cargo[cargo_t] - trans_amg) >= 0 \
                          else src.cargo[cargo_t]
    #print 'trans_amg', trans_amg
    assert trans_amg >= 0
    return trans_amg

def receive_cargo(src, dst, accept_list=None):
    '''receive cargo from `src` to `dst`'''
    cargos = list(set(src.cargotypes_out).intersection(dst.cargotypes_in))
    print 'cargos to transfer:', cargos #, '//', src.cargotypes_out, dst.cargotypes_in
    for cargo_t in cargos:
        if is_empty(src, cargo_t):
            print '%s doesn\'t have %s to transfer, skipping' % (type(src).__name__, cargo_t)
            continue
        dst.cargo.setdefault(cargo_t, 0)
        while True: 
            amg = get_max_transfer_amg(src, dst, cargo_t)
            if not amg:
                print 'nothing to transfer'
                break
            src.cargo[cargo_t] -= amg
            dst.cargo[cargo_t] += amg
            print 'pong:', type(src).__name__, '->', type(dst).__name__, \
                src.cargo[cargo_t], dst.cargo[cargo_t]

def is_empty(obj, cargo_t):
    return True if obj.cargo.get(cargo_t, 0) == 0 else False

def is_full(obj, cargo_t):
    return True if obj.cargo.get(cargo_t, 0) == obj.get_capacity(cargo_t) else False
